<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">
          {{ isEdit ? '编辑易耗品计划' : '创建易耗品计划' }}
        </h2>
      </div>
    </div>

    <div class="max-w-6xl mx-auto">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="semester" class="block text-sm font-medium text-gray-700">学期 *</label>
                <select
                  id="semester"
                  v-model="form.semester"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择学期</option>
                  <option value="2024-1">2024年春季学期</option>
                  <option value="2024-2">2024年秋季学期</option>
                  <option value="2025-1">2025年春季学期</option>
                  <option value="2025-2">2025年秋季学期</option>
                </select>
                <p v-if="errors.semester" class="mt-1 text-sm text-red-600">{{ errors.semester }}</p>
              </div>

              <div>
                <label for="laboratory" class="block text-sm font-medium text-gray-700">实验室 *</label>
                <select
                  id="laboratory"
                  v-model="form.laboratory"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择实验室</option>
                  <option value="计算机实验室A">计算机实验室A</option>
                  <option value="计算机实验室B">计算机实验室B</option>
                  <option value="化学实验室">化学实验室</option>
                  <option value="生物实验室">生物实验室</option>
                  <option value="物理实验室">物理实验室</option>
                </select>
                <p v-if="errors.laboratory" class="mt-1 text-sm text-red-600">{{ errors.laboratory }}</p>
              </div>

              <div class="md:col-span-2">
                <label for="description" class="block text-sm font-medium text-gray-700">计划说明</label>
                <textarea
                  id="description"
                  v-model="form.description"
                  rows="3"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入计划说明"
                ></textarea>
                <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
              </div>
            </div>
          </div>

          <!-- 易耗品项目 -->
          <div>
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-medium text-gray-900">易耗品项目</h3>
              <button
                type="button"
                @click="addItem"
                class="flex items-center px-3 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
              >
                <PlusIcon class="h-4 w-4 mr-1" />
                添加项目
              </button>
            </div>

            <div v-if="form.items.length === 0" class="text-center py-8 text-gray-500">
              <DocumentTextIcon class="h-12 w-12 mx-auto mb-4 text-gray-300" />
              <p>暂无易耗品项目，请点击"添加项目"按钮添加</p>
            </div>

            <div v-else class="space-y-4">
              <div
                v-for="(item, index) in form.items"
                :key="index"
                class="border border-gray-200 rounded-lg p-4"
              >
                <div class="flex justify-between items-center mb-4">
                  <h4 class="text-sm font-medium text-gray-700">项目 {{ index + 1 }}</h4>
                  <button
                    type="button"
                    @click="removeItem(index)"
                    class="text-red-600 hover:text-red-800 focus:outline-none"
                  >
                    <TrashIcon class="h-4 w-4" />
                  </button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                  <div>
                    <label :for="`itemName_${index}`" class="block text-sm font-medium text-gray-700">物品名称 *</label>
                    <input
                      :id="`itemName_${index}`"
                      v-model="item.name"
                      type="text"
                      required
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="请输入物品名称"
                    />
                  </div>

                  <div>
                    <label :for="`itemSpec_${index}`" class="block text-sm font-medium text-gray-700">规格型号</label>
                    <input
                      :id="`itemSpec_${index}`"
                      v-model="item.specification"
                      type="text"
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="请输入规格型号"
                    />
                  </div>

                  <div>
                    <label :for="`itemQuantity_${index}`" class="block text-sm font-medium text-gray-700">计划数量 *</label>
                    <input
                      :id="`itemQuantity_${index}`"
                      v-model.number="item.quantity"
                      type="number"
                      required
                      min="1"
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="请输入数量"
                    />
                  </div>

                  <div>
                    <label :for="`itemUnit_${index}`" class="block text-sm font-medium text-gray-700">单位 *</label>
                    <select
                      :id="`itemUnit_${index}`"
                      v-model="item.unit"
                      required
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    >
                      <option value="">请选择单位</option>
                      <option value="个">个</option>
                      <option value="台">台</option>
                      <option value="套">套</option>
                      <option value="盒">盒</option>
                      <option value="包">包</option>
                      <option value="支">支</option>
                      <option value="瓶">瓶</option>
                      <option value="米">米</option>
                      <option value="千克">千克</option>
                      <option value="升">升</option>
                    </select>
                  </div>

                  <div>
                    <label :for="`itemUnitPrice_${index}`" class="block text-sm font-medium text-gray-700">预估单价 *</label>
                    <input
                      :id="`itemUnitPrice_${index}`"
                      v-model.number="item.unitPrice"
                      type="number"
                      required
                      min="0"
                      step="0.01"
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="请输入单价"
                    />
                  </div>

                  <div class="md:col-span-4">
                    <label :for="`itemPurpose_${index}`" class="block text-sm font-medium text-gray-700">用途说明</label>
                    <textarea
                      :id="`itemPurpose_${index}`"
                      v-model="item.purpose"
                      rows="2"
                      class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="请输入用途说明"
                    ></textarea>
                  </div>
                </div>

                <div class="mt-2 text-right text-sm text-gray-600">
                  小计: ¥{{ (item.quantity * item.unitPrice).toLocaleString() }}
                </div>
              </div>
            </div>

            <!-- 预算汇总 -->
            <div v-if="form.items.length > 0" class="mt-6 bg-gray-50 rounded-lg p-4">
              <div class="flex justify-between items-center">
                <span class="text-lg font-medium text-gray-900">预算汇总</span>
                <span class="text-2xl font-bold text-indigo-600">¥{{ totalBudget.toLocaleString() }}</span>
              </div>
              <div class="mt-2 text-sm text-gray-600">
                共 {{ form.items.length }} 个项目
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
            <button
              type="button"
              @click="$router.back()"
              class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              取消
            </button>
            <button
              type="button"
              @click="saveDraft"
              :disabled="loading"
              class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ loading ? '保存中...' : '保存草稿' }}
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ loading ? '提交中...' : '提交计划' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeftIcon,
  PlusIcon,
  TrashIcon,
  DocumentTextIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const isEdit = computed(() => !!route.params.id)

const form = reactive({
  semester: '',
  laboratory: '',
  description: '',
  items: []
})

const errors = reactive({})

// 计算总预算
const totalBudget = computed(() => {
  return form.items.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0)
})

// 添加项目
const addItem = () => {
  form.items.push({
    name: '',
    specification: '',
    quantity: 1,
    unit: '个',
    unitPrice: 0,
    purpose: ''
  })
}

// 删除项目
const removeItem = (index) => {
  form.items.splice(index, 1)
}

// 验证表单
const validateForm = () => {
  // 清空之前的错误
  Object.keys(errors).forEach(key => delete errors[key])
  
  let isValid = true

  if (!form.semester) {
    errors.semester = '请选择学期'
    isValid = false
  }

  if (!form.laboratory) {
    errors.laboratory = '请选择实验室'
    isValid = false
  }

  if (form.items.length === 0) {
    showMessage('请至少添加一个易耗品项目', 'error')
    isValid = false
  }

  // 验证每个项目
  form.items.forEach((item, index) => {
    if (!item.name) {
      showMessage(`第${index + 1}个项目的物品名称不能为空`, 'error')
      isValid = false
    }
    if (!item.quantity || item.quantity <= 0) {
      showMessage(`第${index + 1}个项目的数量必须大于0`, 'error')
      isValid = false
    }
    if (!item.unitPrice || item.unitPrice < 0) {
      showMessage(`第${index + 1}个项目的单价不能小于0`, 'error')
      isValid = false
    }
  })

  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    loading.value = true
    
    // 实验室名称到ID的映射
    const laboratoryIdMap = {
      '计算机实验室A': 1,
      '计算机实验室B': 2,
      '化学实验室': 3,
      '生物实验室': 4,
      '物理实验室': 5
    }
    
    // 构建请求数据
    const requestData = {
      semester: form.semester,
      laboratoryId: laboratoryIdMap[form.laboratory],
      description: form.description,
      items: form.items.map(item => ({
        name: item.name,
        specification: item.specification,
        unit: item.unit || '个', // 添加单位字段，默认为'个'
        plannedQuantity: item.quantity,
        unitPrice: item.unitPrice
      }))
    }
    
    if (isEdit.value) {
      // 更新计划
      await request.put(`/consumable-plans/${route.params.id}`, requestData)
      showMessage('计划更新成功', 'success')
    } else {
      // 创建计划
      await request.post('/consumable-plans', requestData)
      showMessage('计划提交成功', 'success')
    }
    
    router.push('/consumable-plans')
    
  } catch (error) {
    console.error('提交计划失败:', error)
    showMessage('提交计划失败', 'error')
  } finally {
    loading.value = false
  }
}

// 保存草稿
const saveDraft = async () => {
  if (!form.semester || !form.laboratory) {
    showMessage('请填写基本信息和至少一个易耗品项目', 'error')
    return
  }

  try {
    loading.value = true
    
    // 实验室名称到ID的映射
    const laboratoryIdMap = {
      '计算机实验室A': 1,
      '计算机实验室B': 2,
      '化学实验室': 3,
      '生物实验室': 4,
      '物理实验室': 5
    }
    
    // 构建请求数据
    const requestData = {
      semester: form.semester,
      laboratoryId: laboratoryIdMap[form.laboratory],
      description: form.description,
      status: 'DRAFT', // 草稿状态
      items: form.items.map(item => ({
        name: item.name,
        specification: item.specification,
        unit: item.unit || '个', // 添加单位字段，默认为'个'
        plannedQuantity: item.quantity,
        unitPrice: item.unitPrice
      }))
    }
    
    if (isEdit.value) {
      // 更新草稿
      await request.put(`/consumable-plans/${route.params.id}`, requestData)
    } else {
      // 创建草稿
      await request.post('/consumable-plans', requestData)
    }
    
    showMessage('草稿保存成功', 'success')
    router.push('/consumable-plans')
    
  } catch (error) {
    console.error('保存草稿失败:', error)
    showMessage('保存草稿失败', 'error')
  } finally {
    loading.value = false
  }
}

// 加载计划数据（编辑时）
const loadPlan = async () => {
  if (!isEdit.value) return

  try {
    loading.value = true
    const planId = route.params.id
    
    // 调用真实API加载计划数据
    const response = await request.get(`/consumable-plans/${planId}`)
    const plan = response.data
    
    // 映射API数据到表单字段
    form.semester = plan.semester || ''
    form.laboratory = plan.laboratoryId || ''
    form.description = plan.description || ''
    form.items = plan.items || []
    
  } catch (error) {
    console.error('加载计划数据失败:', error)
    showMessage('加载计划数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadPlan()
  // 默认添加一个项目
  if (!isEdit.value) {
    addItem()
  }
})
</script>